//
//  SelectScreen.m
//  Playlist
//
//  Created by fjaros on 10/19/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SelectScreen.h"
#import "ListView.h"


@implementation SelectScreen
@synthesize bottomBar;
@synthesize viewButton;
@synthesize editButton;
@synthesize deleteButton;
@synthesize playButton;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewWillAppear:(BOOL)animated
{
    UIImage *whichButton;
    if (musicPlayer.playbackState == MPMusicPlaybackStatePlaying)
    {
        isPlaying = YES;
        whichButton = [UIImage imageNamed:@"pause.png"];
    }
    else
    {
        isPlaying = NO;
        whichButton = [UIImage imageNamed:@"play.png"];
    }
    [[self playButton] setImage:whichButton forState:UIControlStateNormal];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Do any additional setup after loading the view from its nib.
    
    musicPlayer = [[MPMusicPlayerController alloc] init];
    [musicPlayer retain];
    
    [self.navigationItem setTitle:@"Select Playlist"];   
    NSArray * temp = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    documentsPath = [temp objectAtIndex:0];
    [self loadAllLists];
    [self showPlaylists];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

//------------------------------------------------------------------------------------------------
// =Ben's custom select screen functions go here!

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) 
    {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }
    
    cell.textLabel.text = [[allPlists objectAtIndex:indexPath.row] stringByReplacingOccurrencesOfString:@".stuff" withString:@""];
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    tView = tableView;
    return [allPlists count];
}

-(void)showPlaylists
{
    //playLists = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"playlists" ofType:@"plist"]];
    //[playLists retain];
    
}

-(void)loadAllLists
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *location = [paths objectAtIndex:0];
    NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:location error:nil];
    allPlists = [dirContents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self ENDSWITH '.stuff'"]];
    [allPlists retain];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    selectedPlaylist = cell.textLabel.text; //This gets the value out of the table cell and stores it in a global variable
}


-(IBAction)viewButtonPushed
{
    ListView *detailedViewController = [[ListView alloc] initWithNibName:@"ListView" bundle:nil];
    
    detailedViewController.currentPlaylist = selectedPlaylist;
    
    // Push new view onto the view stack
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] init];
	backButton.title = @"Back";
	self.navigationItem.backBarButtonItem = backButton;
	[backButton release];
    [self.navigationController pushViewController:detailedViewController animated:YES];
    [detailedViewController release];
}

-(IBAction)editButtonPushed
{
    CreateScreen *cs = [[[CreateScreen alloc] initWithNibName:@"CreateScreen" bundle:nil] autorelease];
    cs.isEditScreen = YES;
    cs.playListName = selectedPlaylist;
    
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] init];
	backButton.title = @"Back";
	self.navigationItem.backBarButtonItem = backButton;
	[backButton release];
    
    [self.navigationController pushViewController:cs animated:YES];
}

-(IBAction)deleteButtonPushed
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *dirPath = [paths objectAtIndex:0];
    NSString *plPath = [dirPath stringByAppendingFormat:@"/%@.stuff", selectedPlaylist];
    BOOL fileExists = [fileManager fileExistsAtPath:plPath];
    if (fileExists) 
    {
        [fileManager removeItemAtPath:plPath error:nil];
        [self loadAllLists];
        [tView reloadData];
    }
}

-(IBAction)playButtonPushed
{
    UIImage *whichButton = [UIImage imageNamed:@"play.png"];
    if (!isPlaying) {
        isPlaying = TRUE;
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *location = [[paths objectAtIndex:0] stringByAppendingFormat:@"/%@.stuff", selectedPlaylist];
        MPMediaItemCollection * bart = [NSKeyedUnarchiver unarchiveObjectWithFile:location];
        [musicPlayer setQueueWithItemCollection:bart];
        [musicPlayer play];
        
        whichButton = [UIImage imageNamed:@"pause.png"];
    }
    else 
    {
        isPlaying = FALSE;
        [musicPlayer pause];
    }
    [[self playButton] setImage:whichButton forState:UIControlStateNormal];
}

@end
